package com.xhsj.user.sms.process.web;

import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.sms.process.entity.TbPurchaseProcessHiTask;
import com.xhsj.user.sms.process.vo.SaveOrderSubTaskVo;
import com.xhsj.user.sms.purchase.entity.TbPurchaseOrderSubtask;
import com.xhsj.user.sms.purchase.entity.TbPurchaseSubtaskList;
import com.xhsj.user.sms.purchase.entity.TbPurchaseTask;
import com.xhsj.user.sms.purchase.query.*;
import com.xhsj.user.sms.purchase.service.TbPurchaseOrderService;
import com.xhsj.user.sms.purchase.service.TbPurchaseTaskService;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import io.swagger.annotations.Api;


import com.xhsj.user.sms.process.service.TbPurchaseProcessTaskService;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;


/**
 * <p>
 * 任务表 前端控制器
 * </p>
 *
 * @author suxiaolin
 * @since 2020-03-16
 */
@Slf4j
@Api(tags = "任务表")
@RestController
@RequestMapping("/process/tbPurchaseProcessTask")
public class TbPurchaseProcessTaskController {

    //角色名称 综合管理部负责人
    @Value("${rolekeyname.administrationDepartment}")
    private String administrationDepartment;

    //角色名称 总经理
    @Value("${rolekeyname.generalManager}")
    private String generalManager;

    //角色名称 采购经理
    @Value("${rolekeyname.purchaseManager}")
    private String purchaseManager;

    //角色名称 财务主管
    @Value("${rolekeyname.financialManager}")
    private String financialManager;

    // 出纳
    @Value("${rolekeyname.teller}")
    private String teller;

    //法务
    @Value("${rolekeyname.legalAffairs}")
    private String legalAffairs;

    //品质经理
    @Value("${rolekeyname.qualityManager}")
    private String qualityManager;

    //仓管经理
    @Value("${rolekeyname.warehouseManager}")
    private String warehouseManager;

    @Autowired
    private TbPurchaseOrderService tbPurchaseOrderService;


    @Autowired
    public TbPurchaseProcessTaskService service;

    @Autowired
    private TbPurchaseTaskService tbPurchaseTaskService;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;



//    @ApiOperation(value = "部门审批", notes = "部门审批")
//    @RequestMapping(value = "/epartmentalApproval", method = RequestMethod.POST)
//    public Message epartmentalApproval(@RequestBody @Valid SmsApprovalQuery data, BindingResult bindingResult) {
//        try {
//            log.info("部门审批参数{}", data);
//            if (bindingResult.hasErrors()) {
//                log.info(bindingResult.getFieldError().getDefaultMessage());
//                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
//            }
//            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) { //通过
//                // 归口部门id
//                Integer relevantDeptId = data.getRelevantDeptId();
//                // 归口部门领导
//                List<String> deptLeader = tbGlobalUserService.getDeptLeader(String.valueOf(relevantDeptId));
//                if (deptLeader ==null || deptLeader.size() == 0) {
//                    return Message.error(1,"归口部门领导不存在,请联系管理员添加相关人员");
//                }
//                data.setUserId(deptLeader);
//            } else if (StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {//退回
//                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
//            }else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1){
//                return Message.error(1,"Status参数只能为0，1");
//            }
//            service.execProcess(data);
//            service.sendMessage(data);
//            return Message.success("保存成功");
//        } catch (Exception e) {
//            log.error("保存失败:{}", e);
//            return Message.error(1,"保存失败");
//        }
//    }

    @ApiOperation(value = "部门审批", notes = "部门审批")
    @RequestMapping(value = "/epartmentalApproval", method = RequestMethod.POST)
    public Message epartmentalApproval(@RequestBody @Valid SmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("审批参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) { //通过
                this.getDesigneeRole(data,purchaseManager);

                TbPurchaseTask tbPurchaseTask = new TbPurchaseTask();
                tbPurchaseTask.setId(data.getDataId());
                tbPurchaseTask.setAuditStatus("1");

                boolean b = tbPurchaseTaskService.updateById(tbPurchaseTask);
                if (!b) {
                    return Message.error(1,"保存采购任务异常");
                }

            } else if (StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {//退回
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            }else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1){
                return Message.error(1,"Status参数只能为0，1");
            }
            service.execProcess(data);

            // 发送消息到采购经理
            this.getDesigneeRole(data,purchaseManager);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    /**
     * 财务审核采购订单
     * @author 苏小林
     * @date 2020/6/9 18:25
     * @return: com.xhsj.user.sms.utils.Message
     */
    @ApiOperation(value = "财务审核采购订单", notes = "财务审核采购订单")
    @RequestMapping(value = "/financialAuditOrder", method = RequestMethod.POST)
    public Message financialAuditOrder(@RequestBody @Valid SmsApprovalQuery data, BindingResult bindingResult){
        try {
            log.info("财务审核采购订单{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }

            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) { //通过
                //根据角色名查找角色
//                List<String> roleKeyNameList=new ArrayList<>();
//                roleKeyNameList.add(generalManager);
//                Set<String> roleIds = tbGlobalUserService.getRoleListByRoleKeyName(roleKeyNameList);
//                data.setRoleIds(roleIds);
                this.getDesigneeRole(data,generalManager);
            } else if (StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {//退回
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            }else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1){
                return Message.error(1,"Status参数只能为0，1");
            }
            service.execProcess(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,e.getMessage());
        }
    }

    /**
     * 总经理审核采购订单
     * @author 苏小林
     * @date 2020/6/10 9:43
     */
    @ApiOperation(value = "总经理审核采购订单", notes = "总经理审核采购订单")
    @RequestMapping(value = "/generalManagerAuditOrder", method = RequestMethod.POST)
    public Message generalManagerAuditOrder(@RequestBody @Valid SmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("总经理审核采购订单{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }

            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {
                data.setProcessType("1");
                // 修改订单审核状态
                int i = tbPurchaseOrderService.updateAuditStatus(data.getDataId());
            }else if (StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {//退回
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            }else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1){
                return Message.error(1,"Status参数只能为0，1");
            }
            // 第一阶段审核
            service.execProcess(data);
            // 第二阶段审核 添加采购订单到审核表
            service.execPurchaseOrder(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    /**
     * 采购经理退回到申请人
     * @author 苏小林
     * @date 2020/6/10 9:43
     */
    @ApiOperation(value = "采购经理退回到申请人", notes = "采购经理退回到申请人")
    @RequestMapping(value = "/purchaseManagerBackToProposerId", method = RequestMethod.POST)
    public Message purchaseManagerBackToProposerId(@RequestBody @Valid SmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("采购经理退回到申请人{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            TbPurchaseTask tbPurchaseTask = tbPurchaseTaskService.getById(data.getDataId());
            tbPurchaseTask.setId(data.getDataId());
            tbPurchaseTask.setAssignUserName("");
            tbPurchaseTask.setAuditStatus("0");

            boolean b = tbPurchaseTaskService.updateById(tbPurchaseTask);
            if (!b) {
                return Message.error(1,"保存采购任务异常");
            }
            data.setUserId(Arrays.asList(tbPurchaseTask.getCreateBy().split(",")));
            service.execProcess(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "创建人重新提交", notes = "创建人重新提交")
    @RequestMapping(value = "/resubmit", method = RequestMethod.POST)
    public Message resubmit(@RequestBody Map<String,Object> data, BindingResult bindingResult) {
        try {
            log.info("创建人重新提交参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.get("status")) == 0 && StringUtils.toInteger(data.get("submitStatus")) == 2) { //通过
                // 查询领导
                String leader = tbGlobalUserService.getLeaderByUserId(StringUtils.toLong(data.get("createBy")));
                if (StringUtils.isBlank(leader)) {
                    return Message.error(1,"部门领导不存在,请联系管理员添加相关人员");
                }

                data.put("userId",Arrays.asList(leader.split(",")));
            }
            service.resubmit(data);
            service.sendMessage(StringUtils.toJavaBean(data, SmsApprovalQuery.class));
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }

    }


    /**
     * 采购经理审核采购员编写采购订单
     * @author 苏小林
     * @date 2020/5/27 10:50
     * @param: data
     * @param: bindingResult
     * @return: com.xhsj.user.sms.utils.Message
     */
    @ApiOperation(value = "采购经理审核采购员编写采购订单", notes = "采购经理审核采购文件")
    @RequestMapping(value = "/purchaseManagerAudit", method = RequestMethod.POST)
    public Message purchaseManagerAudit(@RequestBody @Valid PurchaseOrderQuerySms data, BindingResult bindingResult) {
        try {
            log.info("采购经理审核采购文件{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }

            if (data.getStatus() == 0) {// 审核通过-财务审核

                // 查询财务角色列表
//                List<String> roleNameList=new ArrayList<>();
//                roleNameList.add(financialManager);
//                Set<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleKeyName(roleNameList);
//                data.setRoleIds(roleListByRoleName);
                this.getDesigneeRole(data,financialManager);

            } else if (data.getStatus() == 1) {// 审核退回
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            }
            
            service.execProcess(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }


    /**
     * 采购经理审核采购订单子任务
     * @author 苏小林
     * @date 2020/5/27 10:50
     * @param: data
     * @param: bindingResult
     * @return: com.xhsj.user.sms.utils.Message
     */
    @ApiOperation(value = "采购经理审核采购订单子任务", notes = "采购经理审核采购订单子任务")
    @RequestMapping(value = "/purchaseManagerAuditSubTask", method = RequestMethod.POST)
    public Message purchaseManagerAuditSubTask(@RequestBody @Valid PurchaseOrderQuerySms data, BindingResult bindingResult) {
        try {
            log.info("采购经理审核采购订单子任务{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }

            if (data.getStatus() == 0) {// 审核通过-总经理审核

                // 查询财务角色列表
//                List<String> roleNameList=new ArrayList<>();
//                roleNameList.add(generalManager);
//                Set<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleKeyName(roleNameList);
//                data.setRoleIds(roleListByRoleName);
                this.getDesigneeRole(data,generalManager);
            } else if (data.getStatus() == 1) {// 审核退回
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            }

            service.execProcessOrderSubtask(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "供应链部付款方式，采购合同", notes = "供应链部付款方式，采购合同")
    @RequestMapping(value = "/payContractApproval", method = RequestMethod.POST)
    public Message payContractApproval(@RequestBody @Valid PayContractQuerySms data, BindingResult bindingResult) {
        try {
            log.info("供应链部付款方式，采购合同参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if(StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {
              //总经理
                //根据角色名查找角色
//                List<String> roleKeyNameList=new ArrayList<>();
//                roleKeyNameList.add(generalManager);
//                Set<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleKeyName(roleKeyNameList);
//                data.setRoleIds(roleListByRoleName);
                this.getDesigneeRole(data,generalManager);
            }   if(StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {}else if(StringUtils.toInteger(data.getStatus()) != 0) {
                return Message.error(1,"总经理审批准备采购文件Status参数只能为0");
            }
            service.payContractApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

//    @ApiOperation(value = "法务财务审批付款方式，采购合同", notes = "法务财务审批付款方式，采购合同")
//    @RequestMapping(value = "/legalFinancePayContractApproval", method = RequestMethod.POST)
//    public Message legalFinancePayContractApproval(@RequestBody @Valid PurchaseOrderQuerySms data, BindingResult bindingResult) {
//        try {
//            log.info("法务财务审批付款方式，采购合同参数{}", data);
//            if (bindingResult.hasErrors()) {
//                log.info(bindingResult.getFieldError().getDefaultMessage());
//                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
//            }
//            if(StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {
//                //根据角色名查找角色
//                this.getDesigneeRole(data,generalManager);
//            }else if(StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {
//                //根据角色名查找角色
//                this.getDesigneeRole(data,purchaseManager);
//            }else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1) {
//                return Message.error(1,"总经理审批准备采购文件Status参数只能为0");
//            }
//            service.execProcessOrderAllPass(data);
//            service.sendMessage(data);
//            return Message.success("保存成功");
//        } catch (Exception e) {
//            log.error("保存失败:{}", e);
//            return Message.error(1,"保存失败");
//        }
//    }

    @ApiOperation(value = "总经理审批付款方式，采购合同", notes = "总经理审批付款方式，采购合同")
    @RequestMapping(value = "/managerPayContractApproval", method = RequestMethod.POST)
    public Message managerPayContractApproval(@RequestBody @Valid PurchaseOrderQuerySms data, BindingResult bindingResult) {
        try {
            log.info("总经理审批付款方式，采购合同参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if((StringUtils.toInteger(data.getStatus()) == 0 || StringUtils.toInteger(data.getStatus()) == 1) && data.getSubmitStatus() == 2) {
                //根据角色名查找角色
                this.getDesigneeRole(data,generalManager);
            }else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1) {
                return Message.error(1,"总经理审批准备采购文件Status参数只能为0");
            }
            service.execProcessOrder(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "供应链部内签合同会签合同上传合同文件", notes = "供应链部内签合同会签合同上传合同文件")
    @RequestMapping(value = "/uploadContractFileApproval", method = RequestMethod.POST)
    public Message uploadContractFileApproval(@RequestBody @Valid UploadContractFileQuerySms data, BindingResult bindingResult) {
        try {
            log.info("供应链部内签合同会签合同上传合同文件参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if(data.getStatus() == 3 && data.getSubmitStatus() == 2) { //上传采购合同及预付款申请-比例为0
                //采购文件编写员
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
            } else if(tbGlobalUserService.getCgManager(data.getProposerId(),purchaseManager)&& data.getSubmitStatus() == 2){ //上传采购合同及预付款申请-总经理领导审核
                //根据角色名查找角色 总经理
                data.setStatus(0);
                this.getDesigneeRole(data,generalManager);
            } else if(data.getSubmitStatus() == 2) {
                data.setStatus(8);  //上传采购合同及预付款申请-部门领导审核
                //采购经理
                this.getDesigneeRole(data,purchaseManager);
//                String leader = tbGlobalUserService.getLeaderByUserId(StringUtils.toLong(data.getCreateBy()));
//                data.setUserId(Arrays.asList(leader.split(",")));
            }
            service.uploadContractFileApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "总经理审核低值/固值付款申请", notes = "总经理审核低值/固值付款申请")
    @RequestMapping(value = "/managerLSValuePayApproval", method = RequestMethod.POST)
    public Message managerLSValuePayApproval(@RequestBody @Valid ManagerLSValuePaySmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("总经理审核低值/固值付款申请参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if(data.getSubmitStatus() == 2){
                if(StringUtils.toInteger(data.getStatus()) == 0) {
                    data.setStatus(0);
                    this.getDesigneeRole(data,teller);
                    data.setAuditStatus("0");
                }else {
                    //编写文件得人员
                    data.setUserId(Arrays.asList(data.getProposerId().split(",")));
                    data.setStatus(1);
                    data.setAuditStatus("1");
                }
            }
            service.managerLSValuePayApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "审批预付款，二期款，尾款", notes = "审批预付款，二期款，尾款")
    @RequestMapping(value = "/managerInstallmentPayApproval", method = RequestMethod.POST)
    public Message managerInstallmentPayApproval(@RequestBody @Valid ManagerLSValuePaySmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("审批预付款，二期款，尾款参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {
                data.setAuditStatus("0");
                if(tbGlobalUserService.getCgManager(data.getCreateBy(),purchaseManager)){
                    //根据角色名查找角色
                    this.getDesigneeRole(data,generalManager);
                }else {
                    //根据角色名查找角色
                    this.getDesigneeRole(data,teller);
                }
            } else if (StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
                data.setAuditStatus("1");
            } else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1){
                return Message.error(1,"总经理审批预付款，二期款，尾款Status参数只能为0,1");
            }
            service.InstallmentApprovalPayApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }


    @ApiOperation(value = "低值/固资/预付款/二期款-上传支付凭证", notes = "低值/固资/预付款/二期款-上传支付凭证")
    @RequestMapping(value = "/financeLSValuePayApproval", method = RequestMethod.POST)
    public Message financeLSValuePayApproval(@RequestBody @Valid FinanceLSValuePaySmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("财务低值/固值/预付款/二期款/尾款付款参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {

                String createBy = data.getCreateBy();
                List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(Long.parseLong(createBy));
                if (roleNames.contains(teller)) {// 如果是出纳
                    this.getDesigneeRole(data,financialManager);
                    service.uploadBillOfCredit(data);
                } else {
                    //采购文件编写员
                    data.setUserId(Arrays.asList(data.getProposerId().split(",")));
                    service.financeLSValuePayApproval(data);
                }

            } else if(StringUtils.toInteger(data.getStatus()) != 0){
                return Message.error(1,"供应链部门申请付款Status参数只能为0");
            }
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "供应链部核对采购清单/上传报检清单", notes = "核对采购清单/上传报检清单")
    @RequestMapping(value = "/checkPurchaseListApproval", method = RequestMethod.POST)
    public Message checkPurchaseListApproval(@RequestBody @Valid CheckPurchaseListSmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("供应链部核对采购清单/上传报检清单参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {
                // 获取归口部门领导
                if(StringUtils.isBlank(data.getRelevantDeptId())) {
                    // 根据角色名查找角色品质
                    getDesigneeRole(data,qualityManager);
                }else{
                    // 获取归口部门领导
                    List<String> deptLeader = tbGlobalUserService.getDeptLeader(String.valueOf(data.getRelevantDeptId()));
                    data.setUserId(deptLeader);
                }

            } else if(StringUtils.toInteger(data.getStatus()) != 0){
                return Message.error(1,"供应链部门申请付款Status参数只能为0");
            }
            service.checkPurchaseListApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }


    @ApiOperation(value = "质检记录", notes = "质检记录")
    @RequestMapping(value = "/checkPurchaseRecordApproval", method = RequestMethod.POST)
    public Message checkPurchaseRecordApproval(@RequestBody @Valid CheckPurchaseRecordSmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("质检记录参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
               service.checkPurchaseRecordApproval(data);
               service.sendMessage(data);
               return Message.success("保存成功");

        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "仓管部入库", notes = "仓管部入库")
    @RequestMapping(value = "/storageApproval", method = RequestMethod.POST)
    public Message storageApproval(@RequestBody @Valid StorageSmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("仓管部入库参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            Message message = service.storageApproval(data);
            service.sendMessage(data);
            return message;
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    //退换
    @ApiOperation(value = "退换货", notes = "退换货")
    @RequestMapping(value = "/returnAndExchangeApproval", method = RequestMethod.POST)
    public Message returnAndExchangeApproval(@RequestBody @Valid ReturnAndExchangeQuerySms data, BindingResult bindingResult ) {
        try {
            log.info("退换参数{}", data);
            if (bindingResult.hasErrors()) {
                    log.info(bindingResult.getFieldError().getDefaultMessage());
                    return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
                   }
            service.returnAndExchangeApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    /**
     *
     * @param dataId 业务id
     * @param businessNegotiation 商务协调0 未开启 1开启
     * @return
     */
    //发起商务协调
    @ApiOperation(value = "发起商务协调", notes = "发起商务协调")
    @RequestMapping(value = "/businessNegotiationApproval", method = RequestMethod.GET)
    public Message businessNegotiationApproval(@RequestParam String dataId, int businessNegotiation) {
        try {
            if(service.businessNegotiationApproval(dataId,businessNegotiation)){
                return Message.success("保存成功");
            }
            return Message.error(1,"保存失败");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }


    //关闭终止合同
    @ApiOperation(value = "关闭终止合同", notes = "关闭终止合同")
    @PostMapping(value = "/closeTerminationContractApproval")
    public Message closeTerminationContractApproval(@RequestBody @Valid CloseTerminationContractApprovalQuery data,BindingResult bindingResult) {
        try {
            log.info("发起终止合同参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if(service.closeTerminationContractApproval(data)){
                return Message.success("保存成功");
            }
            return Message.error(1,"保存失败");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    //发起终止合同
    @ApiOperation(value = "发起终止合同", notes = "发起终止合同")
    @PostMapping(value = "/terminationContractApproval")
    public Message terminationContractApproval(@RequestBody @Valid TerminationContractSmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("发起终止合同参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }

            if(service.terminationContractApproval(data)){
                service.sendMessage(data);
                return Message.success("保存成功");
            }
            return Message.error(1,"保存失败");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    //发起终止合同
    @ApiOperation(value = "终止合同回传文件", notes = "终止合同回传文件")
    @PostMapping(value = "/terminationContractReturnFileApproval")
    public Message terminationContractReturnFileApproval(@RequestBody @Valid TerminationContractReturnFileQuerySms data, BindingResult bindingResult) {
        try {
            log.info("终止合同回传文件参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
                //到总经理
                if (tbGlobalUserService.getCgManager(data.getCreateBy(), purchaseManager) && data.getSubmitStatus() == 2) {
                    this.getDesigneeRole(data,generalManager);
                    data.setStatus(8);
                }else {
                    //采购经理
                    this.getDesigneeRole(data,purchaseManager);
                    data.setStatus(0);
                }
                service.terminationContractReturnFileApproval(data);
                service.sendMessage(data);
                return Message.success("成功");

        } catch (Exception e) {
            log.error("成功:{}", e);
            return Message.error(1,"失败");
        }
    }

    //指派人为角色的
    public void getDesigneeRole(@RequestBody @Valid SmsApprovalQuery data, String roleKey) throws Exception {
        List<String> roleKeyNameList = new ArrayList<>();
        roleKeyNameList.add(roleKey);
        Set<String> roleListByRoleName = tbGlobalUserMapper.getRoleListByRoleKeyName(roleKeyNameList);
        if (roleListByRoleName ==null || roleListByRoleName.size() == 0) {
            throw new Exception("下一节点审核角色不存在,请联系管理员添加相关角色");
        }
        data.setRoleIds(roleListByRoleName);
    }


    @ApiOperation(value = "订单结束", notes = "订单结束")
    @PostMapping(value = "/closeOrderApproval")
    public Message endOrderApproval(@RequestBody @Valid CloseOrderQuery data,BindingResult bindingResult) {
        try {
            log.info("订单结束参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            data.setProcessType("3");
            service.endContractOrderApproval(data);
            return Message.success("成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "审批终止合同付款申请", notes = "审批终止合同付款申请")
    @RequestMapping(value = "/contractPayApproval", method = RequestMethod.POST)
    public Message contractPayApproval(@RequestBody @Valid ManagerLSValuePaySmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("审批终止合同付款申请参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.getStatus()) == 0 && data.getSubmitStatus() == 2) {
                //根据角色名查找角色
                if(tbGlobalUserService.getCgManager(data.getCreateBy(),purchaseManager)){
                    getDesigneeRole(data,generalManager);
                }else{
                    getDesigneeRole(data,teller);
                }

                data.setAuditStatus("0");
            } else if (StringUtils.toInteger(data.getStatus()) == 1 && data.getSubmitStatus() == 2) {
                data.setUserId(Arrays.asList(data.getProposerId().split(",")));
                data.setAuditStatus("1");
            } else if(StringUtils.toInteger(data.getStatus()) != 0 && StringUtils.toInteger(data.getStatus()) != 1){
                return Message.error(1,"审批终止合同付款申请Status参数只能为0,1");
            }
            service.managerContractPayApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "财务终止合同付款", notes = "财务终止合同付款")
    @RequestMapping(value = "/financeContractPayApproval", method = RequestMethod.POST)
    public Message financeContractPayApproval(@RequestBody @Valid EndOrderQuerySms data, BindingResult bindingResult) {
        try {
            log.info("财务终止合同付款{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if (StringUtils.toInteger(data.getStatus()) == 0) {
                String createBy = data.getCreateBy();
                List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(Long.parseLong(createBy));
                if (roleNames.contains(teller)) {// 如果是出纳
                    service.uploadContractBillOfCredit(data);
                } else {
                    service.financeContractPayApproval(data);
                }

            } else if(StringUtils.toInteger(data.getStatus()) != 0){
                return Message.error(1,"财务终止合同付款Status参数只能为0");
            }
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    //二期款申请
    @ApiOperation(value = "二期款申请", notes = "二期款申请")
    @RequestMapping(value = "/secondInstallmentApproval", method = RequestMethod.POST)
    public Message secondInstallmentApproval(@RequestBody @Valid PaymentQuerySms data, BindingResult bindingResult) {
        try {
            log.info("二期款申请参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
                if(tbGlobalUserService.getCgManager(data.getProposerId(),purchaseManager) && data.getSubmitStatus() == 2){
                    //总经理
                    data.setStatus(0);
                    this.getDesigneeRole(data,generalManager);
                }else if(data.getSubmitStatus() == 2){
                    data.setStatus(8);
                    //采购经理
                    this.getDesigneeRole(data,purchaseManager);
                }
            service.installmentApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }


    //尾款申请
    @ApiOperation(value = "尾款申请", notes = "尾款申请")
    @RequestMapping(value = "/finalInstallmentApproval", method = RequestMethod.POST)
    public Message finalInstallmentApproval(@RequestBody @Valid PaymentQuerySms data, BindingResult bindingResult) {
        try {
            log.info("尾款申请参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            if(tbGlobalUserService.getCgManager(data.getProposerId(),purchaseManager) && data.getSubmitStatus() == 2) {
                //根据角色名查找角色
                data.setStatus(0);
                this.getDesigneeRole(data,generalManager);
            }else if(data.getSubmitStatus() == 2){
                //部门领导审批
                data.setStatus(8);
                //采购经理
                this.getDesigneeRole(data,purchaseManager);
            }
            service.installmentApproval(data);
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    @ApiOperation(value = "财务尾款付款-上传支付凭证", notes = "财务尾款付款-上传支付凭证")
    @RequestMapping(value = "/financeFinalProportionPayApproval", method = RequestMethod.POST)
    public Message financeFinalProportionPayApproval(@RequestBody @Valid FinanceLSValuePaySmsApprovalQuery data, BindingResult bindingResult) {
        try {
            log.info("财务尾款付款参数{}", data);
            if (bindingResult.hasErrors()) {
                log.info(bindingResult.getFieldError().getDefaultMessage());
                return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
            }

            if (StringUtils.toInteger(data.getStatus()) == 0 ) {
                String createBy = data.getCreateBy();
                List<String> roleNames = tbGlobalUserMapper.getRoleKeyNamesByUserId(Long.parseLong(createBy));
                if (roleNames.contains(teller)) {// 如果是出纳
                    this.getDesigneeRole(data,financialManager);
                    service.uploadBillOfCredit(data);
                } else {
                    service.financeLSValuePayApproval(data);
                    Thread.sleep(1000);
                    TbPurchaseProcessHiTask tbPurchaseProcessHiTask = new TbPurchaseProcessHiTask("", data.getDataId(), "3812CE6C40334DCDAE35DC5E5621B887", 0, data.getProposerId(), data.getCreateBy(), "2");
                    service.saveProcessHiTask(tbPurchaseProcessHiTask);
                }

            } else if(StringUtils.toInteger(data.getStatus()) != 0){
                return Message.error(1,"财务尾款付款Status参数只能为0");
            }
            service.sendMessage(data);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }
    }

    /**
     * 保存采购订单
     * @author 苏小林
     * @date 2020/6/9 14:57
     * @param: tbPurchaseOrderListQuery
     * @param: bindingResult
     * @return: com.xhsj.user.sms.utils.Message
     */
    @ApiOperation(value = "创建采购订单", notes = "创建采购订单")
    @RequestMapping(value = "/savePurchaseOrder", method = RequestMethod.POST)
    public Message savePurchaseOrder(@RequestBody @Valid TbPurchaseOrderListQuery tbPurchaseOrderListQuery,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
        }

        try {
            service.savePurchaseOrderList(tbPurchaseOrderListQuery);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }

    }

    /**
     * 保存采购订单子任务
     * @author 苏小林
     * @date 2020/6/10 18:39
     * @param: tbPurchaseOrderSubtask
     */
    @ApiOperation(value = "保存采购订单子任务", notes = "保存采购订单子任务")
    @RequestMapping(value = "/saveOrderSubTask", method = RequestMethod.POST)
    public Message saveOrderSubTask(@RequestBody SaveOrderSubTaskVo saveOrderSubTaskVo) {
        try {

            service.saveOrderSubTask(saveOrderSubTaskVo);
            return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return Message.error(1,"保存失败");
        }

    }

    @ApiOperation(value = "查询审核任务数据", notes = "查询审核任务数据。")
    @RequestMapping(value="/findAll",method = RequestMethod.GET)
    public Message findAll(){
        return Message.success("成功",service.selectAll());
    }

}

